package com.steak.orm.service.impl;

import com.steak.orm.factory.SQLBuilderInstanceFactory;
import com.steak.orm.service.IQuery;
import com.steak.orm.datasource.JdbcTemplate;
import com.steak.orm.datasource.RowMapper;
import com.steak.orm.tool.StringUtil;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.util.List;

/**
 * @author 刘牌
 * @Title:
 * @date 2022/3/322:35
 */
public class Query<T> extends JdbcTemplate implements IQuery<T> {

    @Override
    public List<T> query(T t) throws Exception {
        String sql = SQLBuilderInstanceFactory.getQueryBuilder().querySql(t);
        System.out.println("sql  "+sql);
        Field[] fields = t.getClass().getDeclaredFields();
        return executeQuery(sql, new RowMapper<T>() {
            @Override
            public T mapRow(ResultSet resultSet) throws Exception {
                for (Field field : fields) {
                    String getField = StringUtil.getSetMethod(StringUtil.getLastStr(field.toString()));
                    Object object = resultSet.getObject(StringUtil.getLastStr(field.toString()), field.getType());
                    t.getClass().getMethod(getField,field.getType()).invoke(t,object);
                }
                return t;
            }
        });
    }
}
